/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.third.etc.feeclouds.service;

import com.google.api.client.util.Lists;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.third.etc.feeclouds.constant.enums.FeecloudsConstant;
import org.jeecg.modules.third.etc.feeclouds.dto.HistoryOrderEndDTO;
import org.jeecg.modules.third.etc.feeclouds.utils.MD5Util;
import org.jeecg.modules.third.jg.report.freight.information.util.WebUtils;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 路耕ETC发票服务平台接口
 *
 * @author duanlikao
 * @created 2021/9/6
 */
@Service
public class EtcFeecloudsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(EtcFeecloudsService.class);

    @Value(value="${etc-feeclouds.baseurl}")
    private String BASEURL;

    /**
     *
     * @param kvMap
     * @param path
     * @param method
     * @return
     */
    public  String invokeFee( Map<String, String> kvMap,  String path, String method) {

        HyConfig systemConfig = HyConfigUtils.getConfig();
        if(systemConfig == null || !systemConfig.getEtcFeecloudsIzUse()){
            throw new JeecgBootException("路耕ETC上报服务暂未开启,请联系管理员。");
        }

        if(MapUtils.isEmpty(kvMap)){
            throw new JeecgBootException("请求数据不能为空。");
        }
        if(StringUtils.isBlank(path)){
            throw new JeecgBootException("请求路径地址不能为空。");

        }

        String  url = BASEURL +path;
        kvMap.put("company_key", systemConfig.getEtcFeecloudsKey());
        //6位随机字符串
        kvMap.put("nonce_str", UUIDGenerator.getRandomStr());

        Map <String, String> ignore = new HashMap <>();
        Map <String, String> resultMap = new HashMap <>();
        ArrayList <String> keys = Lists.newArrayList(kvMap.keySet());
        Collections.sort(keys);
        try {
            StringBuilder params = new StringBuilder();
            for (String key : keys) {
                params.append(key);
                params.append("=");
                params.append(kvMap.get(key));
                params.append("&");
                resultMap.put(key, kvMap.get(key).toString());
            }
            params.append(URLEncoder.encode("company_secret", "utf-8"));
            params.append("=");
            params.append(URLEncoder.encode(systemConfig.getEtcFeecloudsSecrect(), "utf-8"));

            String md5 = MD5Util.md5(params.toString());
            resultMap.put("sign", md5.toUpperCase());
        } catch (Exception e) {
            LOGGER.error("EtcFeecloudsService invokeFee ======>>签名失败:", e.getMessage());
            return StringUtils.EMPTY;
        }
        if (ignore != null) {
            resultMap.putAll(ignore);
        }
        String content = null;
        try {
            if("GET".equals(method)){
                content = WebUtils.doGet(url, resultMap);
              //  content = new JacksonJsonParser().parseMap(entity);
            }else{
                content = WebUtils.doPostBuildQuery(url, resultMap , WebUtils.DEFAULT_CHARSET,null);
               // content = new JacksonJsonParser().parseMap(postEntity.getContent());
            }
        } catch (Exception e) {
            LOGGER.error("EtcFeecloudsService invokeFee  failed: ", e.getMessage());
            return StringUtils.EMPTY;
        }
        if (StringUtils.isNotEmpty(content)) {
            return content ;
        }
        return StringUtils.EMPTY;
    }




    public static void main(String[] args) {

        EtcFeecloudsService etcFeecloudsService =  new EtcFeecloudsService();

//        String  path = FeecloudsConstant.VEHICLE_REGISTER_API_PATH;
//        Map <String, String> dtoMap = CommonUtils.beanToMap(
//                new VehicleRegisterDTO()
//                        .setPlate_number("苏H06032")
//                        .setPlate_color("1")
//                        .setTaxno(FeecloudsConstant.COMPANY_TAXNO)
//                ) ;

//        String  path =  FeecloudsConstant.ORDER_HISTORY_START_API_PATH;
//        Map <String, String> dtoMap = CommonUtils.beanToMap(
//                new HistoryOrderStartDTO()
//                        .setNum("YD202109051708139052")
//                        .setPlate_number("苏H06032")
//                        .setPlate_color("1")
//                        .setStart_time("2021-09-01T17:08:13")
//                        .setPredict_end_time("2021-09-03T17:08:13")
//                        .setSource_addr("邢台市柏乡县")
//                        .setDest_addr("天津是和平区")
//                        .setFee(238974)
//                        .setTaxno(FeecloudsConstant.COMPANY_TAXNO)
//        ) ;

        String  path =  FeecloudsConstant.ORDER_HISTORY_END_API_PATH ;
        Map <String, String> dtoMap = CommonUtils.beanToMap(
                new HistoryOrderEndDTO()
                        .setNum("YD202109051708139052")
                        .setEnd_time("2021-09-03T17:08:13")
                        .setReal_dest_addr("天津是和平区")

        ) ;


        String reponse = etcFeecloudsService.invokeFee(dtoMap ,path,"POST");

        System.out.println(reponse);


//        System.out.println(etcFeecloudsService.getRandomStr());


//        URL url = new URL("http://www.example.com/some/path/to/a/file.xml?foo=bar#test");
//        System.out.println(FilenameUtils.getBaseName(url.getPath())); // -> file
//        System.out.println(FilenameUtils.getExtension(url.getPath())); // -> xml
//        System.out.println(FilenameUtils.getName(url.getPath())); // -> file.xml
    }


}
